const db = require('../db/connection');

class QueryService {
  constructor() {
    this.cache = new Map();
  }

  async queryTable(params) {
    const { country, table, product, filters = {}, page = 1, pageSize = 20 } = params;

    if (!this.validateParams(params)) {
      return this.createErrorResponse('Invalid parameters');
    }

    try {
      const sql = this.buildQuery(table, filters, page, pageSize);
      const results = await db.query(country, sql);
      
      return this.createSuccessResponse(table, results);
    } catch (error) {
      console.error('Query error:', error);
      return this.createErrorResponse('Database query failed');
    }
  }

  validateParams(params) {
    const { country, table, product } = params;
    return country && table && product;
  }

  buildQuery(table, filters, page, pageSize) {
    let sql = `SELECT * FROM ${table} WHERE 1=1`;
    
    // Add filters
    Object.entries(filters).forEach(([key, value]) => {
      if (value) {
        sql += ` AND ${key} = '${value}'`;
      }
    });

    // Add pagination
    const offset = (page - 1) * pageSize;
    sql += ` ORDER BY create_time DESC LIMIT ${pageSize} OFFSET ${offset}`;

    return sql;
  }

  createSuccessResponse(table, data) {
    return {
      code: '0',
      data: {
        table,
        list: data
      },
      msg: 'success'
    };
  }

  createErrorResponse(message) {
    return {
      code: '-1',
      data: {
        table: '',
        list: []
      },
      msg: message
    };
  }
}

module.exports = new QueryService(); 